<?php

/*
 * Usage:
 * 
 * Call:		parcel_by_coord.php?lat=<lat>&lng=<lng>
 * Returns: 	JSON data structure for parcel
 * 				
 */


ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');

require_once 'JSON.php';
$json = new Services_JSON();

// get lat and lng
$lat = $_GET["lat"];
$lng = $_GET["lng"];

/*
      SELECT parcel_add 
      FROM parcels 
      WHERE WITHIN(
      PointFromText('POINT(-111.8491 40.7105)', 4326),
      the_geom);
            
*/


$query_parcel = "SELECT parcel_add, AsText(the_geom) FROM parcels WHERE WITHIN(PointFromText('POINT($lat $lng)', 4326),the_geom)";
print $query_parcel;
exit;

$parcels = array();

// connect to db
$conn = pg_connect("dbname=rvha user=pgadmin password=pgadmin");
	if (!$conn)
	{
       	 	print "Unable to Connect to DB";
	        exit;
	}

// PARCEL
$result_parcel = pg_query($query_parcel);
while ($arr = pg_fetch_array($result_parcel))
{
	$parcel = new Parcel();
	$parcel->address = $arr[0];
	
	// parse multipolygons
	$multi = $arr[1];
	$multi = preg_replace("/MULTIPOLYGON\((.*)\)/", "$1", $multi);
	$polys = preg_split("/\),\(/", $multi);

	for($i=0; $i<=sizeof($polys)-1; $i++)
	{
		
		$polygon = new Polygon();
		
		// clean up the double surrounding brackets
		$poly = preg_replace("/\(\((.*)\)\)/", "$1", $polys[$i]);
		
		// parse points
		$points = split(",", $poly);
		for($j = 0; $j <= sizeof($points)-1; $j++)
		{
			
			$point = new LatLng();
			
			$p = $points[$j];
			//print $p . "<br>";
			// now split point on ' '
			$coords = split(" ", $p);
			$lng = $coords[0];
			$lat = $coords[1];
			//print "lat=$lat, lng=$lng<br>";
			
			$point->lat = $lat;
			$point->lng = $lng;
			//print_r($point);
			
			$polygon->addPoint($point);
			
		}
		
		$parcel->addPolygon($polygon);
		
	}
	
	
	// split ... on commas
	// loop over array from split
	// now we have a single POLYGON
	// split on comma again to separate points
	// for each point, split on ' ' (space)
	// 	[0] = lng, [1] = lat
	array_push($parcels, $parcel);
}

$jsonWrapper = '{"parcel-response":{"parcels":';
$jsonWrapper .= $json->encode($parcels);
$jsonWrapper .= '}';


print $jsonWrapper;

class Parcel {
	
	var $address;
	var $polygons = array();
	
	function Parcel()
	{

	}	
	
	function addPolygon($polygon)
	{
		array_push($this->polygons, $polygon);
	}
}

class Polygon {
	
	var $points = array();
	
	function Polygon()
	{
		
	}
	
	function addPoint($point)
	{
		array_push($this->points, $point);
	}	
	
}

class LatLng {
	
	var $lat;
	var $lng;
	
	function Polygon()
	{
		
	}	
	
}
?>